//
//  HLNeteworkTool.swift
//  HLwWeibo
//
//  Created by hqhxu on 16/2/27.
//  Copyright © 2016年 hqhxu. All rights reserved.
//

import UIKit
import AFNetworking

/*
swift中枚举是值类型  就是他的值的是确定的 
类是指针类型
*/
// 自定义错误使用枚举类型
enum HLNetworkingError:Int {
    
    //定义成员变量值
    case Access_tokenEnmpty = -1
    case UidEnmpty = -2
    
    // 属性
    var errorMessage:String {
        //只有一个get方法时可以省略get关键字
        switch self {
        case Access_tokenEnmpty:
            return "Access_tokenEnmpty没有值"
        case UidEnmpty:
            return "UidEnmpty没有值"
        }
    }
    // 方法
    func error() -> NSError {
        
        let error = NSError(domain: "cn.Netorking.com", code: self.rawValue, userInfo: ["errorMessage":errorMessage])
        
        return error
    }
}

class HLNeteworkTool: NSObject {

    var manager:AFHTTPSessionManager
    
    // 相当于oc中的typedef把这个中定义为
    typealias finshedCallBack = (response:AnyObject?,error:NSError?) -> Void
    
    static let shareInstance = HLNeteworkTool()
    
    /*
    content-type: text/plain 不能识别这个类型
    */
    private override init() {
        // 会自动判断如果有https的话那么就不会加上baseurl 如果么有就会加上
        let baseUrl = NSURL(string: "https://api.weibo.com/")
        
        manager = AFHTTPSessionManager(baseURL: baseUrl)
        //增加response解析器的可以解析的类型
        manager.responseSerializer.acceptableContentTypes?.insert("text/plain")
    }
    
    let othUrl = "https://api.weibo.com/oauth2/authorize"
    let client_id = "3054723419"
    let redirect_uri = "http://www.baidu.com"
    
    func ouathUrl() -> NSURL{
        
        let urlStr  = othUrl + "?" + "client_id=" + client_id + "&" + "redirect_uri=" + redirect_uri
        
        return NSURL(string: urlStr)!
    }
    
    /*
    https://api.weibo.com/oauth2/access_token
    client_id 	true 	string 	申请应用时分配的AppKey。
    client_secret 	true 	string 	申请应用时分配的AppSecret。
    grant_type 	true 	string 	请求的类型，填写authorization_code
    
    
    grant_type为authorization_code时
    
    必选 	类型及范围 	说明
    code 	true 	string 	调用authorize获得的code值。
    redirect_uri 	true 	string 	回调地址，需需与注册应用里的回调地址一致。
    */
    
    
    let url = "https://api.weibo.com/oauth2/access_token"
    let client_secret = "1402310c46c47c42f48c8ebbe08cacbf"
    let grant_type = "authorization_code"
    
    func loadAccess_token(code:String,finshedeClosure:finshedCallBack) {
        
        var param:[String:String] = [:]
        param["client_id"] = client_id
        param["client_secret"] = client_secret
        param["grant_type"] = grant_type
        param["code"] = code
        param["redirect_uri"] = redirect_uri
        
        manager.POST(url, parameters: param, progress:nil , success: { (_, response) -> Void in
            
            // 执行闭包 把返回的数据传出去
            finshedeClosure(response: response, error: nil)
            
            }) { (_, error) -> Void in
                
                print("请求失败error:\(error)")
                
                finshedeClosure(response: nil, error: error)
                
        }
    }
    
    /// 加载用户信息  用户头像和昵称
    func loadUserInform(finshedClouse:finshedCallBack) {
        var param:[String:String] = [:]
        /*
        access_token 	true 	string 	采用OAuth授权方式为必填参数，OAuth授权后获得。
        uid 	false 	int64 	需要查询的用户ID。
        */
        
        
//        HLAccountViewModel.shareInstance.userAcount?.uid = nil //测试uid为空
        let uid = HLAccountViewModel.shareInstance.userAcount?.uid
        
//        HLAccountViewModel.shareInstance.userAcount?.access_token = nil // 测试access_token为空
        let access_token = HLAccountViewModel.shareInstance.userAcount?.access_token
        
        guard uid != nil else {
            let error = HLNetworkingError.UidEnmpty.error()
            
            finshedClouse(response: nil, error: error)
            return
        }
        
        guard access_token != nil else {
            let error = HLNetworkingError.Access_tokenEnmpty.error()
            finshedClouse(response: nil, error: error)
            
            return
        }
        
        param["access_token"] = access_token
        param["uid"] = uid
        
        GET("https://api.weibo.com/2/users/show.json", parameters: param) { (resopense, error) -> Void in
            if resopense != nil {
                finshedClouse(response: resopense, error: nil)
            } else {
                finshedClouse(response: nil , error: error)
            }
        }
    }
    
    
    /// 加载微博数据
    func loadStatusData(since_id:Int?,max_id:Int?,finshedClosure:finshedCallBack) {
        
        var params = [String:AnyObject]()
        
        let access_token = HLAccountViewModel.shareInstance.userAcount?.access_token
        
        params["access_token"] = access_token
        // 守卫
        guard access_token != nil else {
            
            let error = HLNetworkingError.Access_tokenEnmpty.error()
            finshedClosure(response: nil, error: error)
            return
        }
        if since_id > 0 {
            params["since_id"] = since_id
        }
        
        if max_id > 0 {
            params["max_id"] = max_id! - 1
        }
        
        GET("https://api.weibo.com/2/statuses/home_timeline.json", parameters: params, finshedClosure: finshedClosure)
        /*
        GET("https://api.weibo.com/2/statuses/home_timeline.json", parameters: params) { (resopense, error) -> Void in
            if resopense != nil {
                finshedClosure(response: resopense, error: nil)
            }else {
                print("error:\(error)")
                finshedClosure(response: nil, error: error)
            }
        }
*/
        
    }
    
    
    /// 网络请求封装
    private func GET(URLString:String,parameters:AnyObject?,finshedClosure:(resopense:AnyObject?,error:NSError?) ->Void) {
        manager.GET(URLString, parameters: parameters, progress: nil, success: { (_, resopense) -> Void in
            
            finshedClosure(resopense: resopense, error: nil)
            
            }) { (_, error) -> Void in
                
            finshedClosure(resopense: nil, error: error)
                
        }
    }
    
    
    
}
